import React from 'react';
import Api from 'Utils/api';
import { Menu, Icon, message, notification } from 'antd';
import { connect } from 'react-redux';
import { WEBRTC_APPID } from 'Constants/config';
import { BROWSER_MODE } from 'Constants/webConstants';
import TitleButton from 'Component/Page/Components/TitleButton';
import './index.scss';

class SuperviseOnLinePage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      openKeys: '11',
      userInfo: {},
      stopImg: false,
      isConnect: false
    };
    this.websocketConnect = ::this.websocketConnect;
    this.sendRequest = ::this.sendRequest;
    this.sendRequest = ::this.sendRequest;
    this.connectChannel = ::this.connectChannel;
    this.returnStatus = ::this.returnStatus;
    this.handleStop = ::this.handleStop;
  }
  componentWillMount() {
    this.initData();
    this.initUserInfo();
  }
  componentWillUnmount() {
    this.handleStop();
  }
  initUserInfo() {
    const api = new Api({
      method: 'POST',
      path: '/login/guest',
      success: (res) => {
        this.setState({
          userInfo: res
        }, () => {
          this.websocketConnect(res);
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  websocketConnect(userInfo) {
    const socket = new SockJS(`${window.config.API_HOST}/gs-guide-websocket?socket_auth=${userInfo.socket_auth}`);
    this.stompClient = Stomp.over(socket);
    this.stompClient.connect({}, () => {
      this.connectSub = this.stompClient.subscribe(`/topic/guest.${userInfo.id}/chat`, (res) => {
        console.log('res', res);
        //showGreeting(JSON.parse(greeting.body).content);
        const json = JSON.parse(res.body);
        const result = json.result;
        const type = json.type;
        console.log('type', type);
        console.log('result', result);
        console.log(result === 0);
        if (type === 'chat_req_result') {
          if (result === 1) {
            this.setState({
              stopImg: true,
              isConnect: true
            });
            this.initData();
            this.connectChannel(json.channelKey, json.chatId);
          }
          if (result === 2) {
            console.log('refuse');
            notification.warning({
              message: '通知',
              description: '对方拒绝了您的连接请求',
              duration: 6
            });
          }
        }
        console.log(res);
      });
      this.stompClient.subscribe('/topic/guest/public', (res) => {
        console.log(res);
        this.initData();
        /*const json = JSON.parse(res);
        console.log(json);
        if (json.status === 1) {
          console.log('online');
          this.initData();
        } else if (json.status === 0) {
          console.log('off');
          this.initData();
        }*/
      });
    });
  }
  initData() {
    const api = new Api({
      method: 'GET',
      path: '/depts',
      success: (json) => {
        console.log(json);
        this.setState({
          data: json
        });
      },
      error: () => {}
    });
    api.run();
  }
  sendRequest(depId) {
    this.stompClient.send('/app/chat/req', {},
      JSON.stringify({ targetDeptId: depId }));
  }
  connectChannel(channelkey, chatId) {
    const self = this;
    this.client = AgoraRTC.createClient();
    this.client.init(WEBRTC_APPID,
      () => {
        //加入 AgoraRTC 频道(join)
        this.client.join(channelkey, chatId, this.state.userInfo.id,
          () => {
            //创建音视频对象
            this.localStream = AgoraRTC.createStream({
              streamID: parseInt(this.state.userInfo.id, 10),
              audio: true,
              video: true,
              screen: false,
            });
            window.localStream = this.localStream;
            //this.localStream.setVideoProfile('360P_8');
            // 初始化音视频流对象
            this.localStream.init(() => {
              // console.log('init local video');
              // if (this.localStream) {
              //   this.client.unpublish(this.localStream, (err) => {
              //     console.log('Unpublish failed with error: ', err);
              //   });
              //   this.localStream.close();
              // }
              // 播放本地视频流
              //this.localStream.play('selfVideo', '/images');
              window.stream = this.localStream.stream;
              console.log('enter');
              console.log(window.stream);
              AdapterJS.attachMediaStream(document.getElementById('selfVideo'), window.stream);
              console.log('end');
              // 将本地的视频流上传到服务器
              this.client.publish(this.localStream, (err) => {
                console.log('publish is err', err);
              });
            }, () => {
              // console.log(err);
            });
            // 通知应用程序远程视频流已经添加
            this.client.on('stream-added', (evt) => {
              const stream = evt.stream;
              window.remoteStream = stream;
              console.log('New stream added: ', stream.getId());
              // 订阅远程视频流
              this.client.subscribe(stream, (err) => {
                console.log('subscribe stream failed', err);
              });
            });
            // 接收远程视频流
            this.client.on('stream-subscribed', (evt) => {
              const otherStream = evt.stream;
              console.log('subscible remote is successful', otherStream.getId());
              AdapterJS.attachMediaStream(document.getElementById('otherVideo'), otherStream.stream);
             // otherStream.play('otherVideo', '/images');
            });
            // 远程音视频流已删除回调事件
            this.client.on('stream-removed', (evt) => {
              const stream = evt.stream;
              self.handleStop();
              console.log('remote stream was removed', stream.getId());
            });
            //通知对方已离开会议室
            this.client.on('peer-leave', (evt) => {
              console.log('remote user left ', evt.uid);
              self.handleStop();
            });
          },
          () => {});
      },
      (err) => { console.log(err); });
  }
  handleVideo(e) {
    const state = e.item.props.item.status;
    if (state === 0) {
      notification.info({
        message: '通知',
        description: '正在等待对方的确认，请稍等......',
        duration: 6
      });
      this.sendRequest(e.key);
    }
  }
  handleSubMenu(state, e) {
    if (state === 0) {
      notification.info({
        message: '通知',
        description: '正在等待对方的确认，请稍等......',
        duration: 6
      });
      this.sendRequest(e.key);
    }
  }
  handleStop() {
    if (this.localStream && this.client && this.stompClient) {
      this.localStream.stop();
      this.client.unpublish(this.localStream);
      this.client.unsubscribe(window.remoteStream);
      this.connectSub.unsubscribe();
      this.initData();
      this.initUserInfo();
      AdapterJS.attachMediaStream(document.getElementById('otherVideo'), null);
      AdapterJS.attachMediaStream(document.getElementById('selfVideo'), null);
    }
    if (this.localStream) {
      this.localStream.close();
    }
    this.setState({
      stopImg: false
    });
  }
  renderMenu(config) {
    return (
      <div>
        <Menu
          onOpenChange={this.onMenuClick.bind(this)}
          mode="inline"
          defaultOpenKeys={['1']}
          onClick={this.handleVideo.bind(this)}
         // onSelect={this.hideMenuState.bind(this)}
        >
          {
            config.map((item) => {
              return this.renderMenuItem(item);
            })
          }
        </Menu>
      </div>
    );
  }
  onMenuClick(e) {
    this.setState({
      openKeys: e,
    });
  }
  returnStatus(status) {
    if (status === 0) {
      return (
        <img src="images/icon_video_light.png" alt="连接" className="direct-img" />
      );
    }
    if (status === 1) {
      return (
        <img src="images/icon_video_normal.png" alt="不可连接" className="direct-img" />
      );
    }
    return (
      <img src="images/icon_video_busy.png" alt="忙碌" className="direct-img" />
    );
  }
  renderMenuItem(Pitem) {
    const { openKeys } = this.state;
    const subDepts = Pitem.sub_depts ? Pitem.sub_depts : [];
    if (subDepts.length === 0) {
      return (
        <Menu.Item key={Pitem.id} item={Pitem} disabled={Pitem.state !== 0}>
          <span>
            {Pitem.name}
          </span>
          <span className="sub-label-icon">
            {
              Pitem.state > -1 ? this.returnStatus(Pitem.state) : ''
            }
          </span>
        </Menu.Item>
      );
    }
    return (
      <Menu.SubMenu
        key={Pitem.id}
        item={Pitem}
        onTitleClick={this.handleSubMenu.bind(this, Pitem.state)}
        title={
          <span className="label">
            <Icon type={openKeys.indexOf(Pitem.id.toString()) > -1 ? 'caret-down' : 'caret-right'} />
            {Pitem.name}
            <span className="sub-label-icon">
              {
              Pitem.state > -1 ? this.returnStatus(Pitem.state) : ''
            }
            </span>
          </span>
        }
      >
        {
          Pitem.sub_depts.map((item) => {
            return this.renderMenuItem(item);
          })
        }
      </Menu.SubMenu>
    );
  }
  render() {
    const { data, isConnect } = this.state;
    const { mode } = this.props;
    const isVertical = BROWSER_MODE.isVertical(mode);
    if (isVertical) {
      return (
        <div className="v-supervise-online-page">
          <div className="supervise-online-wrap">
            <TitleButton title="横溪分局监管中心" />
            <div className="back">
              <div className="video-direct">
                {
                  this.state.stopImg ? <img src="images/interactive/icon_video_stop.png" alt="挂断视频" className="stop-video" onClick={this.handleStop.bind(this)} /> : ''
                }
                {
                  isConnect ? <video id="otherVideo" className="other-video" /> : ''
                }
                {
                  isConnect ? <video id="selfVideo" className="self-video" /> : ''
                }
                视频直连
              </div>
              <div className="side-menu">
                {
                  data && data.length > 0 && this.renderMenu(data)
                }
              </div>
            </div>
          </div>
        </div>
      );
    }
    return (
      <div className="supervise-online-page">
        <div className="supervise-online-wrap">
          <TitleButton title="横溪分局监管中心" />
          <div className="back">
            <div className="content">
              <div className="side-menu">
                {
                  data && data.length > 0 && this.renderMenu(data)
                }
              </div>
              <div className="video-direct">
                {
                  this.state.stopImg ? <img src="images/interactive/icon_video_stop.png" alt="挂断视频" className="stop-video" onClick={this.handleStop.bind(this)} /> : ''
                }
                {
                  isConnect ? <video id="otherVideo" className="other-video" /> : ''
                }
                {
                  isConnect ? <video id="selfVideo" className="self-video" /> : ''
                }
                视频直连
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
    ...state.webReducer
  };
}
export default connect(mapStateToProps)(SuperviseOnLinePage);
